from appserver import db_store
from sqlalchemy import or_
from models.entity.sensor import Sensor
from models.entity.model_base import ModelBase

"""
传感器分组表
"""

class SensorGroup(ModelBase):
    __tablename__ = "sensor_groups"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    name = db_store.Column(db_store.String(64),comment=u"传感器分组名称")
    dis_order = db_store.Column(db_store.Integer, comment=u"排序",default=0)
    description = db_store.Column(db_store.String(255),comment=u"分组描述")
    icon = db_store.Column(db_store.String(32),comment="图标")
    code = db_store.Column(db_store.String(32),nullable=False,unique=True,comment="编码")

    def __repr__(self):
        return "<SensorGroup %s>" %self.name

    def to_dict(self):
        rdic={}
        rdic["id"] = self.id
        rdic["name"] = self.name
        rdic["dis_order"] = self.dis_order
        rdic["description"] = self.description
        rdic["icon"] = self.icon
        rdic["code"] = self.code
        sensor_num = len(Sensor.query.filter_by(sensor_group_id=self.id).all())
        rdic["sensor_num"] = sensor_num
        return rdic
    
    @staticmethod
    def search(query_word):
        tmp = {}
        data = []
        sensor_groups = SensorGroup.query.filter(
            or_(SensorGroup.code.like('%' + query_word + '%'), SensorGroup.name.like('%' + query_word + '%'),
                SensorGroup.description.like('%' + query_word + '%'),SensorGroup.dis_order.like('%'+query_word+'%'))).order_by("dis_order").all()
        for obj in sensor_groups:
            data.append(obj.to_dict())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return tmp
